package cn.tedu.hm.service.impl;
import cn.tedu.hm.ex.ServiceException;
import cn.tedu.hm.mapper.OrderMapper;
import cn.tedu.hm.pojo.dto.OrderMakeNewDTO;
import cn.tedu.hm.pojo.dto.OrderUpdateDTO;
import cn.tedu.hm.pojo.entity.Order;
import cn.tedu.hm.pojo.vo.OrderListItemVO;
import cn.tedu.hm.pojo.vo.OrderStandardVO;
import cn.tedu.hm.service.IOrderService;
import cn.tedu.hm.service.IRoomService;
import cn.tedu.hm.wep.JsonPage;
import cn.tedu.hm.wep.ServiceCode;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;

/**
 * 说明:
 *
 * @ author: WeiZhen
 * @date: 2023/3/8
 **/
@Service
@Slf4j
public class OrderServiceImpl implements IOrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Override
    public void getOrderByCardNumber(String cardNumber, String otherCardNumber) {
        log.debug("开始处理根据身份证查询订单的业务，参数：{}，{}", cardNumber, otherCardNumber);
        int rows = orderMapper.selectByCardNumber(cardNumber, otherCardNumber);
        if (rows == 0) {
            String message = "信息输入错误或订单信息不存在";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_CONFLICT, message);
        }
    }

    @Override
    public void makeNew(OrderMakeNewDTO orderMakeNewDTO) {
        log.debug("开始处理生成订单的业务，参数：{}", orderMakeNewDTO);
        int rows = orderMapper.countByRoomId(orderMakeNewDTO.getRoomId());
        if(rows!=0){
            String message = "生成订单失败，该订单的房间已被占用";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_CONFLICT,message);
        }
        //计算价钱
        BigDecimal days = new BigDecimal(orderMakeNewDTO.getDays());
        BigDecimal price = orderMakeNewDTO.getPrice().multiply(days);
        Order order = new Order();
        BeanUtils.copyProperties(orderMakeNewDTO, order);
        order.setPrice(price);
        //生成订单，订单状态默认为 0 待入住
        order.setState(WILL_LIVE);
        //生成订单号
        String orderNumber = UUID.randomUUID().toString();
        order.setOrderNumber(orderNumber);
        //获取生成订单时间
        LocalDateTime startTime = LocalDateTime.now();
        order.setStartTime(startTime);
        int hour = startTime.getHour();
        LocalDateTime endTime = null;
        //判断早于凌晨5点，是，当天12点退房   否，加上入住天数的当天12点退房
        if(hour < BETWEEN_TIMES){
            endTime = startTime.plusDays(orderMakeNewDTO.getDays()-1);
            endTime=endTime.withHour(12).withMinute(0).withSecond(0);
        }else {
            endTime = startTime.plusDays(orderMakeNewDTO.getDays());
            endTime=endTime.withHour(12).withMinute(0).withSecond(0);
        }
        //获取订单结束时间
        order.setEndTime(endTime);
        int row = orderMapper.insert(order);
        if (row != 1) {
            String message = "生成订单失败，服务器忙，请稍后再尝试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_INSERT, message);
        }
    }

    @Override
    public void deleteById(Long id) {
        OrderStandardVO queryResult = orderMapper.getStandardById(id);
        if (queryResult == null) {
            String message = "删除失败，删除的订单数据不存在";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_NOT_FOUND,message);
        }
        log.debug("即将执行删除操作，id为{}",id);
        int rows = orderMapper.deleteById(id);
        if (rows != 1) {
            String message = "删除订单失败，服务器忙，请稍后再尝试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_DELETE, message);
        }
    }

    @Override
    public void updateInfoById(Long id, OrderUpdateDTO orderUpdateDTO) {
        OrderStandardVO queryResult = orderMapper.getStandardById(id);
        if (queryResult == null) {
            String message = "修改失败，修改的订单数据不存在";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_NOT_FOUND,message);
        }
        Order order = new Order();
        BeanUtils.copyProperties(orderUpdateDTO,order);
        order.setId(id);
        int rows = orderMapper.update(order);
        if (rows != 1) {
            String message = "更新订单失败，服务器忙，请稍后再尝试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_UPDATE, message);
        }
    }

    @Override
    public JsonPage<OrderListItemVO> list(Integer page, Integer pageSize) {
        log.debug("开始处理查询订单的处理，当前页：{},条数：{}",page, pageSize);
        PageHelper.startPage(page, pageSize);
        List<OrderListItemVO> queryResult = orderMapper.list();
        log.debug("查询结果为{}",queryResult);
        if (queryResult == null) {
            // 是：抛出异常
            String message = "根据名字模糊查询订单列表失败，订单数据不存在！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_NOT_FOUND, message);
        }
        return JsonPage.restPage(new PageInfo<>(queryResult));
    }

    @Override
    public JsonPage<OrderListItemVO> getListByName(String name, Integer page, Integer pageSize) {
        log.debug("开始处理【根据名字模糊查询订单列表】的业务，参数：{},当前页：{},条数：{}",name, page, pageSize);
        PageHelper.startPage(page, pageSize);
        List<OrderListItemVO> queryResult = orderMapper.getListByName(name);
        if (queryResult == null) {
            // 是：抛出异常
            String message = "根据名字模糊查询订单列表失败，订单数据不存在！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_NOT_FOUND, message);
        }
        return JsonPage.restPage(new PageInfo<>(queryResult));
    }
    @Override
    public JsonPage<OrderListItemVO> getListByPhone(String phone, Integer page, Integer pageSize) {
        log.debug("开始处理【根据电话模糊查询订单列表】的业务，参数：{},当前页：{},条数：{}", phone, page, pageSize);
        PageHelper.startPage(page, pageSize);
        List<OrderListItemVO> queryResult = orderMapper.getListByPhone(phone);
        if (queryResult == null) {
            // 是：抛出异常
            String message = "根据电话模糊查询订单列表失败，订单数据不存在！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_NOT_FOUND, message);
        }
        return JsonPage.restPage(new PageInfo<>(queryResult));
    }

    @Override
    public JsonPage<OrderListItemVO> getHistoryListByName(String name, Integer page, Integer pageSize) {
        log.debug("开始处理【根据名字模糊查询历史订单列表】的业务，参数：{},当前页：{},条数：{}",name, page, pageSize);
        PageHelper.startPage(page, pageSize);
        List<OrderListItemVO> queryResult = orderMapper.getHistoryListByName(name);
        if (queryResult == null) {
            // 是：抛出异常
            String message = "根据名字模糊查询历史订单列表失败，订单数据不存在！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_NOT_FOUND, message);
        }
        return JsonPage.restPage(new PageInfo<>(queryResult));
    }

    @Override
    public JsonPage<OrderListItemVO> getHistoryListByPhone(String phone, Integer page, Integer pageSize) {
        log.debug("开始处理【根据电话模糊查询历史订单列表】的业务，参数：{},当前页：{},条数：{}", phone, page, pageSize);
        PageHelper.startPage(page, pageSize);
        List<OrderListItemVO> queryResult = orderMapper.getHistoryListByPhone(phone);
        if (queryResult == null) {
            // 是：抛出异常
            String message = "根据电话模糊查询历史订单列表失败，订单数据不存在！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_NOT_FOUND, message);
        }
        return JsonPage.restPage(new PageInfo<>(queryResult));
    }

    @Override
    public OrderStandardVO getStandardById(Long id) {
        log.debug("开始处理【根据ID查询订单详情】的业务，参数：{}", id);
        OrderStandardVO queryResult = orderMapper.getStandardById(id);
        if (queryResult == null) {
            // 是：抛出异常
            String message = "查询订单详情失败，订单数据不存在！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_NOT_FOUND, message);
        }
        return queryResult;
    }

    @Override
    public JsonPage<OrderListItemVO> listHistory(Integer page, Integer pageSize) {
        log.debug("开始处理查询历史订单的处理，无参数");
        PageHelper.startPage(page, pageSize);
        List<OrderListItemVO> queryResult = orderMapper.listHistory();
        log.debug("查询结果为{}",queryResult);
        return JsonPage.restPage(new PageInfo<>(queryResult));
    }


}
